package com.luli.Utils;

import ch.ethz.ssh2.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Calendar;
import java.util.Random;

public class FileUtils {

    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);


    /**
     * 创建空白文件
     *
     * @param fileName 文件名
     * @param fileDir  保存文件的目录
     * @return
     */
    public static File createNewFile(String fileName, String fileDir) throws Exception {
        return createNewFile(fileName, fileDir, false);
    }


    /**
     * @param fileName
     * @param fileDir
     * @param isGrant
     * @return
     * @throws Exception
     */
    public static File createNewFile(String fileName, String fileDir, boolean isGrant) throws Exception {
        File fileDirs = new File(fileDir);
        // 看文件夹是否存在，如果不存在新建目录
        if (!fileDirs.exists())
            fileDirs.mkdirs();

        String os = System.getProperty("os.name").toLowerCase();
        logger.debug("audit--->os:" + os);
        if (isGrant) {
            fileDirs.setExecutable(true);//设置可执行权限
            fileDirs.setReadable(true);//设置可读权限
            fileDirs.setWritable(true);//设置可写权限
            if (!os.contains("windows")) {
                String commonds = "chmod 777 -R " + fileDirs.getAbsolutePath();
                logger.debug("audit--->commonds:" + commonds);
                Runtime.getRuntime().exec(commonds);
            }
        }
        // 拼凑文件完成路径
        File file = new File(fileDir + File.separator + fileName);
        file.createNewFile();
        if (isGrant) {
            file.setExecutable(true);//设置可执行权限
            file.setReadable(true);//设置可读权限
            file.setWritable(true);//设置可写权限
            if (!os.contains("windows")) {
                String commonds = "chmod 777 -R " + file.getAbsolutePath();
                logger.debug("audit--->commonds:" + commonds);
                Runtime.getRuntime().exec(commonds);
            }
        }

        return file;
    }

    public static String renameFile(String name) {
        int max = 99999;
        int min = 0;
        String prefix = name.substring(name.lastIndexOf(".") + 1);
        Random random = new Random();
        int randomValue = random.nextInt(max) % (max - min + 1) + min;
        long timeToken = FileUtils.getTimeToken();
        name = String.valueOf(timeToken) + String.valueOf(randomValue) + "." + prefix;
        return name;
    }

    /**
     * 得到当前日期字符串 格式（yyyy-MM-dd）
     */
    public static long getTimeToken() {
        return Calendar.getInstance().getTimeInMillis();
    }


    /**
     * 获取桌面路径
     *
     * @return
     */
    public static String getDesktopPath() {
        FileSystemView fsv = FileSystemView.getFileSystemView();
        File com = fsv.getHomeDirectory();
        return com.getPath();
    }


    //------------------------------------

    /**
     * @Author
     * @Date
     * @Version 1.0
     * <p>备注：远程文件下载到本地 方法二选一<p>
     */


    /**
     * 下载远程文件并保存到本地
     *
     * @param remoteFilePath-远程文件路径
     * @param localFilePath-本地文件路径（带文件名）
     */
    public static void downloadFile1(String remoteFilePath, String localFilePath) {
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f = new File(localFilePath);
        try {
            urlfile = new URL(remoteFilePath);

            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            bos.flush();
            bis.close();
            httpUrl.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 下载远程文件并保存到本地
     *
     * @param remoteFilePath-远程文件路径
     * @param localFilePath-本地文件路径（带文件名）
     */
    public static void downloadFile2(String remoteFilePath, String localFilePath) {
        URL website = null;
        ReadableByteChannel rbc = null;
        FileOutputStream fos = null;
        try {
            website = new URL(remoteFilePath);
            rbc = Channels.newChannel(website.openStream());
            fos = new FileOutputStream(localFilePath);//本地要存储的文件地址 例如：test.txt
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (rbc != null) {
                try {
                    rbc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 小试牛刀
     *
     * @param args
     */
    public static void main(String[] args) throws IOException {
            // 创建服务对象
            RemoteCommandUtil commandUtil = new RemoteCommandUtil();
            // 登录到LInux服务
            Connection root = RemoteCommandUtil.login("120.24.188.179", "root", "NiePeng_!@#");
            // 服务器文件路径
            String fwPath = "/home/myqxin";
            // windows本地存放目录，不需要加上具体文件
            String bdPath = "D:\\Music\\";
            // 下载文件
            commandUtil.downloadFile(root,"鬼刀.png",fwPath,bdPath,null);
            // 批量下载
//      commandUtil.downloadDirFile(root,fwPath,bdPath);
    }


}
